package cn.com.callback

import groovy.json.* //导入grooby的json解析api包
import java.util.Map;
import cn.com.elite.EliteBean;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.Util;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;

import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import org.apache.commons.lang.StringUtils;
import java.lang.*;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.*;
 
public class Robotevent implements ServiceBackInvoke{
    private static final Log log=LogFactory.getLog(Robotevent.class);
    private String charset = "utf-8"; //设置字符集
    private int timeout = 100000; //设置请求超时时间
    private int enableSSLflag = 1;   
    public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response){
		JSONObject result = new JSONObject();

        //获取入参
		def event_guid = request.getParameter("event_guid");
        def ANI=request.getParameter("ANI");
		
			
		if(!event_guid.equals("")&&!ANI.equals("")){
			return rebotinfo(eliteBean,ANI,event_guid);
		}else{
			result.put("msg", "请检查入参！");
            result.put("code", "-1");
            return result;			
		}
    }

    /**
 * 
 * @use 获取呼叫历史信息
 * @param eliteBean
 * @param ANI 手机号码
 * @return
 */

    private String rebotinfo(EliteBean eliteBean,String ANI,String event_guid) {
        JSONObject result = new JSONObject();
	try{
	
		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        def url = "";
        def url_info = "";
		def url_value = "";
        def smap_url = eliteBean.chaxun_sql("select parameter_url as url from sysc_interface where 1=1 and parameter_cord='listCallRecordInbounds'","dataSource");
		def smap1_url = eliteBean.chaxun_sql("select parameter_url as url,parameter_value from sysc_interface where 1=1 and parameter_cord='listChatRecordInbounds'","dataSource");
		
        if(smap_url.size()==0&&smap1_url.size()==0) {
            result.put("msg", "接口地址获取失败！");
            result.put("code", "-1");
            return result;
        }else{
             url =  smap_url[0].getAt("url");
			 url_info = smap1_url[0].getAt("url");
			 url_value = smap1_url[0].getAt("parameter_value");
        };
		
        Map headMap=new HashMap(); //设置头文件
        headMap.put("Content-Type","application/json");
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("beginTime",date.format(new Date()-1));
        jsonBody.put("endTime",date.format(new Date()));
        jsonBody.put("telNumber",ANI);
		jsonBody.put("hangupedByRemote",'null');
        jsonBody.put("beginPage",0);
        jsonBody.put("pageSize",20);
		log.debug("jsonBody传参："+jsonBody);
        def callhis = Util.doHttpPostUseHead(url,jsonBody.toString(),charset,timeout,enableSSLflag,headMap);
		
		log.debug("接口返回当前号码呼叫历史："+callhis);
		
		JSONObject calljson = JSONObject.fromObject(callhis);
        def dataList =  calljson.data.getJSONArray("dataList").get(0);
        def callId = dataList.getAt("callId");   
		
        log.debug("接口返回当前号码呼叫历史："+callId);
		
        if(callId=='') {
             result.put("msg", "未获取到callId！");
             result.put("code", "-2");
             return result;
         }else{
             //接口获取对话记录
            Map headMap1=new HashMap(); //设置头文件
            headMap1.put("Content-Type","application/json");
            headMap1.put("X-EnterpriseID",url_value);
            JSONObject jsonBody1 = new JSONObject();
            jsonBody1.put("callId",callId);
            def chatinfo = Util.doHttpPostUseHead(url_info,jsonBody1.toString(),charset,timeout,enableSSLflag,headMap1);
			
            log.debug("接口返回呼叫ID对话历史："+chatinfo);
			
			JSONObject chatinfojson = JSONObject.fromObject(chatinfo);
			def chatlist =  chatinfojson.data.getJSONArray("chatRecordItemProfiles");
			def i=0;
				if(chatlist.size()>0){
					for(i=0;i<chatlist.size();i++){
						def beginTime = chatlist[i].getAt("beginTime");
						def finishTime = chatlist[i].getAt("finishTime");
						def hasComplaintRisk = chatlist[i].getAt("hasComplaintRisk");
						def hasEmotionAlertInVoice = chatlist[i].getAt("hasEmotionAlertInVoice");
						def hasEmotionAlertInText = chatlist[i].getAt("hasEmotionAlertInText");
						def isRobotSpeaking = chatlist[i].getAt("isRobotSpeaking");
						def content = chatlist[i].getAt("content");
						eliteBean.update("insert into robotcall(callguid,event_guid,callid,beginTime,finishTime,content,hasComplaintRisk,hasEmotionAlertInVoice,hasEmotionAlertInText,isRobotSpeaking)values(newid(),'"+event_guid+"','"+callId+"','"+beginTime+"','"+finishTime+"','"+content+"','"+hasComplaintRisk+"','"+hasEmotionAlertInVoice+"','"+hasEmotionAlertInText+"','"+isRobotSpeaking+"')","dataSource");
					}
				
				}
			 result.put("msg", "调用成功！");
             result.put("code", "1");
             return result;
           
		}
			}catch (Exception e) {
			log.error("errormsg:", e)
			result.put("msg", "接口调用失败！");
			return result;
        }

    }
}
